package com.kaibes.module.token;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kaibes.core.base.util.StringUtils;
import com.kaibes.module.token.core.TokenUtils;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.filter.FilterInternalConfig;

@RestController
@RequestMapping("/token")
public class TokenController {

    @Autowired
    private FilterInternalConfig webConfig;

    @PostMapping
    public void init() {
        webConfig.getPathWhiteList().add("/token/clean");
        webConfig.getPathWhiteList().add("/token/check");
    }

    @GetMapping("clean")
    @ApiLink(value = "清除客户端登录cookie", validated = false)
    public void clean(HttpServletRequest request, HttpServletResponse response) {
        TokenUtils.deleteAllFromCookie(request, response);
        try {
            response.sendRedirect(request.getHeader("Referer"));
        } catch (IOException e) {
        }
    }

    @GetMapping("check")
    @ApiLink(value = "验证是否非法访问", validated = false)
    public void check(HttpServletRequest request, HttpServletResponse response) {
        String url = (String) request.getAttribute("checkUrl");
        System.out.println("checkUrl "+url);
        String body = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>Insert title here</title></head><body><a href=\"#\">正在验证用户合法性。。。</a><script src=\"https://cdn.bootcdn.net/ajax/libs/crypto-js/4.0.0/crypto-js.min.js\"></script><script src=\"/kaibes/js/base.js\"></script><script src=\"/kaibes/js/network.js\"></script><script type=\"text/javascript\">skip('"
                + url + "');</script></body></html>";
        try {
            response.getOutputStream().write(StringUtils.getBytes(body));
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
